<?php
//version 2007-06-06

//2007-04-17 - Added lookup_values function
//2007-05-24 Added refer string to edit part of make_edit_table (fixed)
//2007-06-06 Added get_max_value fucntion, usefull for adding new when you cant get the value of last insert
//2007-07-11 Added array_condense_col
//2007-07-13 Added condense option to make_edit_table 
//2007-07-13 Added make_csv_table and parseCSVComments
//2007-0723 Added text limit of 40 to make_dd option text
// CT 2008-01-04 - Added check for d, r, v in make_array_table
//CT 2008-02-04 - Added make_array_xml, xml_escape and xml_unescape functions
//CT 2008-03-08 - Added make_editable_table, to produce an editable tablef rom an array.
//CT 2008-03-12 - Added checkbox functionality and optional opts array
// CT 2008-04-23 - Bugfix- Added '!empty' check to pass values
// CT 2008-04-23 - Feature - Add checkbox and list functionality to make_editable_table
// CT 2008-04-23 - added options to make_array_list 
// CT 2008-05-05 - MOD - Changed to use mode var, phase out 'rowchange'


// funciton to create a drop-down menu from an array of arrays, reflecting results of a quwery.
// $valuesarray is the array, formed by putting each mysql_fetch_array into a holder array
// $selectname is the name of the select box created
// $showkey is the key (string) of the string to put int he drop-down to have show up
// $valuekey is the key (string) of the data to put in the value = part
// $selectedvalue is the key (string) of the value to show as selected when form is created.
// $query it the query to get the text from
// $text limit is the max length of option text
// CT


// ----------------------------------------------------------------Front End Functions

/*  All in commonctls.php (old header file)
function make_auto_table($thequery, $showvalues, $keyvalues, $actionpage, $referstring)
{
return make_table($thequery, $showvalues, $keyvalues, $mode = "rd", $actionpage, "", $referstring , 'none');
}

function make_edit_table($thequery, $showvalues, $keyvalues, $actionpage, $editpage, $referstring, $condense = 'none')
{
return make_table($thequery, $showvalues, $keyvalues, "rde", $actionpage, $editpage, $referstring , $condense);
}

function make_ed_table($thequery, $showvalues, $keyvalues, $actionpage, $referstring)
{
return make_table($thequery, $showvalues, $keyvalues, "rde", $actionpage, $_SERVER['PHP_SELF'], $referstring , 'none');
}

function make_ro_auto_table($thequery, $showvalues, $keyvalues, $actionpage, $referstring = "")
{
return make_table($thequery, $showvalues, $keyvalues, "ro", $actionpage, "", $referstring , 'none');
}

function make_view_table($thequery, $showvalues, $keyvalues, $actionpage, $editpage, $referstring)
{
return make_table($thequery, $showvalues, $keyvalues, "rv", $actionpage, $editpage, $referstring , 'none');
}


*/



function make_array_dd($valuesarray, $selectname, $showkey,$valuekey,$selectedvalue, $textlimit = 40, $opts = '') {
if(isset($opts['id'])){
	$dd_id = $opts['id'];
}
else{
	$dd_id = $selectname;
}

if(isset($opts['onchangename'])){
	$onchangename = $opts['onchangename'];
	}
else{
	$onchangename = "chg_$selectname";
	}

if(isset($opts['rawformat'])){
	$rawformat = $opts['rawformat'];
}	

if(isset($opts['onchangeparam'])){
	$onchangeparam = $opts['onchangeparam'];
}
	
$atindex = 1;
$dropdowntext .= "<SELECT name=\"";
$dropdowntext .= $selectname;
$dropdowntext .= "\" onChange=\"";
$dropdowntext .= $onchangename;
$dropdowntext .= "($onchangeparam)\" ";
$dropdowntext .= " id=\"";
$dropdowntext .= $dd_id;
$dropdowntext .= "\"> \n";
	if (!empty($valuesarray)) {
		foreach ($valuesarray as $key=>$currentvalue) {
			//$currentvalue=$valuesarray[$atindex];
			$dropdowntext.= "<OPTION ";
			if ($currentvalue[$valuekey] == $selectedvalue) {
				$dropdowntext .= "selected=\"selected\" " ;
				}
			$dropdowntext.= "value=\"";
			$dropdowntext.=$currentvalue[$valuekey];
			$dropdowntext.="\">";
			$dropdowntext.= substr($currentvalue[$showkey],0,$textlimit);
			$dropdowntext.="</OPTION>\n";
			//$atindex++;
			}
		}
	$dropdowntext.= "</SELECT>";
return $dropdowntext;
}










//ct 071107
// Given a properly ordered results set array, this funciton will condense joined results by showing
// all related things in $condensecol column into a comma delimited list
// $inputarray = the intput array of results.  $condensecol = the name of the col in the assoicated array.  $delimiter is a string to delimit the result list
// This funciton returns an array.
function array_condense_col($inputarray, $condensecol, $delimiter = ", " , $prefix = "", $postfix = "" ) {

	// set last row so that it is not the same
	$outkey = "undefined";
	$valueplace = 0;
	$same = 0; // start out with unique row
	foreach($inputarray as $key1 => $currentrow) {
		if (!($valueplace == 0)) {
			// set them to the same until proven otherwise
			$same = 1;
			foreach($currentrow as $key2 => $currentvalue) {
				if(!($key2 == $condensecol)) {
					if(!($currentrow[$key2] == $lastrow[$key2])) {
						$same = 0;
				
					} // ($currentrow[$key2] == $lastrow[$key2])
				} // (!($key2 == $condensecol))
				
			} // ($currentrow as $key2 => $currentvalue)
		} // (!$valueplace == 0)
		$valueplace ++;
		// produce output row
		if($same == 0) { // Things are different, start new output row
			// End last row with postfix
			if (!($outkey == "undefined")) { // Do nothing for the first row
				$outarray[$outkey] [$condensecol] .= $postfix;
			}
			
			// Copy to new array
			$outarray[$key1] = $inputarray[$key1];
			
			//Start new row with prefix
			$outarray[$key1] [$condensecol] = $prefix;
			$outarray[$key1] [$condensecol] .= $inputarray[$key1] [$condensecol];
			
			$outkey = $key1;  // track the last outarray position
			// reset wasnull flag, guard against null for first value and using delimiter when not necessary
			$wasnull = 0;
			}
		else {
			// check against empty set 071307 ct
			$newval = $inputarray[$key1][$condensecol];
			if(!($newval == "")) {
				if($wasnull == 1) {
					$addvalue = $inputarray[$key1][$condensecol];
				} else {
					$addvalue = $delimiter . $inputarray[$key1][$condensecol];
					//print $addvalue;
					$outarray[$outkey] [$condensecol] .= $addvalue;
					$wasnull = 0;
					}
				}
			else { $wasnull = 1; }	
			}
			
				
		$lastrow = $currentrow;
		
	} // foreach $inputarray
	
	return $outarray;

}
// THis function wil parce fields for CSV output.
// from http://www.wlscripting.com/tutorial/37
function parseCSVComments($comments) {
  $comments = str_replace('"', '""', $comments); // First off escape all " and make them ""
  if(eregi(",", $comments) or eregi("\n", $comments)) { // Check if I have any commas or new lines
    return '"'.$comments.'"'; // If I have new lines or commas escape them
  } else {
    return $comments; // If no new lines or commas just return the value
  }
}







// Make csv download out of 2d array.
// $thename = the file name (.csv is added)
// $start text is text passed in to start the string (can be used for title rows)
//  $valuesarray is the array of values (2d)
// $showvalues tells which of the values to show.

function make_csv_array_table($thename, $starttext , $valuesarray, $showvalues){
	$csv_text = $starttext;
	if ($valuesarray) {
	
	// IF values shluod be condensed, use this...(cusomizes function)
		if($condense != 'none') {
			$column = $condense['column'];
			$delimiter = $condense['delimiter'];
			$prefix = $condense['prefix'];
			$postfix = $condense['postfix'];
			$valuesarray = array_condense_col($valuesarray, $column, $delimiter, $prefix, $postfix );
		}
	$row_position = 0;
	foreach($valuesarray as $key1 => $currentrow) {
	
		if($row_position > 0) {
			$csv_text .= "\n";
		}	
	
	$col_position = 0;
		foreach ($currentrow as $key2 => $currentvalue) {
			$value = parseCSVComments($currentvalue);
			
			if($col_position > 0) {
				$csv_text .= ",";
			}
			
			$csv_text .= $value;
			$col_position ++;
			
			}
		$row_position ++;
		
		} // foreach($valuesarray as $key1 => $currentrow)
			// Start our output of the CSV
	header("Content-type: application/x-msdownload");
	header("Content-Disposition: attachment; filename=$thename.csv");
	header("Pragma: no-cache");
	header("Expires: 0");
	echo $headers.$csv_text;
	
	}// end if ($valuesarray)
	else {
		// Nothing needed to be output. Put an error message here or something.
		echo 'No data available for this CSV.';
	}	
}



function make_array_table($valuesarray, $showvalues, $keyvalues, $mode = "ro", $actionpage = "", $editpage = "", $referstring = "")
{

	if(stristr($mode,'d')){
		$delete = 1;
		}
	
	if(stristr($mode, 'e')){
		$edit = 1;
		}
	
	if(stristr($mode, 'v')){
		$view = 1;
		}

	if ($valuesarray) {
		
	foreach($valuesarray as $key1 => $currentrow) {
	//	$table_text .= "<tr>";
	($rowclass == 'odd_row_color')?$rowclass = 'even_row_color':$rowclass = 'odd_row_color';
	$table_text .= "<tr class=\"$rowclass\">";
		foreach ($currentrow as $key2 => $currentvalue) {
			if ($showvalues[$key2] == 1) {
				$table_text .= "<td>";
				$table_text .= $currentvalue;
				$table_text .= "</td>";
			}
		}
		
		if($delete == 1) {
			$table_text .= "<td>";
			$table_text .= "<a href= \"";
			$table_text .= $actionpage;
			$table_text .= "?mode=Delete";
			
			foreach ($currentrow as $key3 => $currentvalue) {
				if ($keyvalues[$key3] == 1) {
					$table_text .= "&";
					$table_text .= $key3;
					$table_text .= "=";
					$table_text .= $currentvalue;
					}
				}
			$table_text .= $referstring;
			$table_text .="\" >Delete </a> </td> ";
		} // if($delete == 1)
		if($edit == 1) {
			$table_text .= "<td> <a href=\"";
			$table_text .= $editpage;
			$table_text .= "?mode=Edit";
			foreach ($currentrow as $key3 => $currentvalue) {
				if ($keyvalues[$key3] == 1) {
					$table_text .= "&";
					$table_text .= $key3;
					$table_text .= "=";
					$table_text .= $currentvalue;
					}
				}
			$table_text .= $referstring;		
			$table_text .= "\" >Edit </a> </td> \n";
			} // if($edit == 1)
				if($view == 1) {
			$table_text .= "<td> <a href=\"";
			$table_text .= $editpage;
			$table_text .= "?mode=View";
			foreach ($currentrow as $key3 => $currentvalue) {
				if ($keyvalues[$key3] == 1) {
					$table_text .= "&";
					$table_text .= $key3;
					$table_text .= "=";
					$table_text .= $currentvalue;
					}
				}
			$table_text .= $referstring;		
			$table_text .= "\" >View </a> </td> \n";
			} // if($view == 1)	
		}
		$table_text .= "</tr> \n";
		
		return $table_text;	
	}
} 

// CT-011508 This version will make a form out of each row, so that changes can be done to the row view.  under construction
function make_ed_array_table($valuesarray, $showvalues, $keyvalues, $mode = "ro", $actionpage = "", $editpage = "", $referstring = "")
{

	if(stristr($mode,'d')){
		$delete = 1;
		}
	
	if(stristr($mode, 'e')){
		$edit = 1;
		}
	
	if(stristr($mode, 'v')){
		$view = 1;
		}

	if ($valuesarray) {
		
	foreach($valuesarray as $key1 => $currentrow) {
	//	$table_text .= "<tr>";
	($rowclass == 'odd_row_color')?$rowclass = 'even_row_color':$rowclass = 'odd_row_color';
	$table_text .= "<form action=\"$actionpage?mode=edit$referstring\" method=\"POST\">
	<tr class=\"$rowclass\">";
		foreach ($currentrow as $key2 => $currentvalue) {
			if (isset($showvalues[$key2])) {
				$table_text .= "<td>";
				$table_text .= $currentvalue;
				$table_text .= "</td>";
			}
		}
		
		if($delete == 1) {
			$table_text .= "<td>";
			$table_text .= "<a href= \"";
			$table_text .= $actionpage;
			$table_text .= "?mode=Delete";
			
			foreach ($currentrow as $key3 => $currentvalue) {
				if (isset($keyvalues[$key3])) {
					$table_text .= "&";
					$table_text .= $key3;
					$table_text .= "=";
					$table_text .= $currentvalue;
					}
				}
			$table_text .= $referstring;
			$table_text .="\" >Delete </a> </td> ";
		} // if($delete == 1)
		if($edit == 1) {
			$table_text .= "<td> <a href=\"";
			$table_text .= $editpage;
			$table_text .= "?mode=Edit";
			foreach ($currentrow as $key3 => $currentvalue) {
				if ($keyvalues[$key3] == 1) {
					$table_text .= "&";
					$table_text .= $key3;
					$table_text .= "=";
					$table_text .= $currentvalue;
					}
				}
			$table_text .= $referstring;		
			$table_text .= "\" >Edit </a> </td> \n";
			} // if($edit == 1)
				if($view == 1) {
			$table_text .= "<td> <a href=\"";
			$table_text .= $editpage;
			$table_text .= "?mode=View";
			foreach ($currentrow as $key3 => $currentvalue) {
				if ($keyvalues[$key3] == 1) {
					$table_text .= "&";
					$table_text .= $key3;
					$table_text .= "=";
					$table_text .= $currentvalue;
					}
				}
			$table_text .= $referstring;		
			$table_text .= "\" >View </a> </td> \n";
			} // if($view == 1)	
		
		$table_text .= "</form></tr> \n";
		}
		return $table_text;	
	}
} 

//  Array to convert to plain text to XML entities .
function xml_escape($input){

$XmlEntities = array(
    '&amp;'  => '&',
    '&lt;'   => '<',
    '&gt;'   => '>',
    '&apos;' => '\'',
    '&quot;' => '"',
);

$realtext = array('&', '<', '>', '\'', '"');
$xmltext = array( '&amp;', '&lt;', '&gt;', '&apos;', '&quot;');

// Seems like only the first line should be necessary, but it didnt work.  odd... for now I'll leave it all there.
$output = str_replace($realtext, $xmltext, $input);
$output = str_replace('&', '&amp;', $output);
$output = str_replace("<", "&lt;", $output);
$output = str_replace('>', '&gt;', $output);
$output = str_replace('\'', '&apos;', $output);
$output = str_replace('"', '&quot;', $output);

return $output;
}
//  Array to convert XML entities back to plain text.
function xml_unescape($input){


$realtext = array('&', '<', '>', '\'', '"');
$xmltext = array( '&amp;', '&lt;', '&gt;', '&apos;', '&quot;');

// Seems like only the first line should be necessary, but it didnt work.  odd... for now I'll leave it all there.
$output = str_replace($xmltext, $realtext, $input);
$output = str_replace('&amp;', '&', $output);
$output = str_replace("&lt;","<", $output);
$output = str_replace('&gt;','>', $output);
$output = str_replace('&apos;','\'', $output);
$output = str_replace('&quot;','"', $output);

return $output;
}

function make_array_xml($valuesarray, $showvalues, $setname = 'resultset'){
	if ($valuesarray) {
	$table_text = "<?xml version=\"1.0\"?>\n";
	$table_text .= "\t<$setname>\n";
		foreach($valuesarray as $key1 => $currentrow) {
			$table_text .= "\t\t<row>\n";
			foreach ($currentrow as $key2 => $currentvalue) {
				if($showvalues[$key2] == 1){
					$table_text .= "\t\t\t<$key2>";
					$table_text .= xml_escape($currentvalue);
					$table_text .= "</$key2>\n";
					}
				
			}
			$table_text .= "\t\t</row>\n";
		}
		$table_text .= "\t</$setname>\n";
		}
	
	return $table_text;
}

function make_array_xsd($valuesarray, $showvalues, $setname = 'resultset'){
	if ($valuesarray) {
	$table_text = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>
<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\"
  targetNamespace=\"urn:yahoo:lcl\"
  xmlns=\"urn:yahoo:lcl\"
  elementFormDefault=\"qualified\">

	<xs:element name=\"$setname\">
		<xs:complexType>
			<xs:sequence>
				<xs:element name=\"ResultSetMapUrl\" type=\"xs:string\" />
				<xs:element name=\"Result\" type=\"ResultType\" minOccurs=\"0\" maxOccurs=\"50\" />
			</xs:sequence>
			<xs:attribute name=\"totalResultsAvailable\" type=\"xs:integer\" />
			<xs:attribute name=\"totalResultsReturned\" type=\"xs:integer\" />
			<xs:attribute name=\"firstResultPosition\" type=\"xs:integer\" />
		</xs:complexType>
	</xs:element>
	
	";
	$table_text .= "
	<xs:complexType name=\"ResultType\">
		<xs:sequence>
";
		//$currentrow = $valuesarray[0];
		foreach($valuesarray as $key1 => $currentrow) {
			//$table_text .= "\t\t<row>\n";
			foreach ($currentrow as $key2 => $currentvalue) {
				if($showvalues[$key2] == 1){
					$table_text .= "\t\t<xs:element name=\"$key2\" type=\"xs:string\" />\n";
					//$table_text .= xml_escape($currentvalue);
					//$table_text .= "</$key2>\n";
					}
				
			}
			//$table_text .= "\t\t</row>\n";
			break; // this works
		}
		$table_text .= "
		</xs:sequence>
	</xs:complexType>
 </xs:schema>";
		}
	
	return $table_text;
}

// ct 2008-03-08
// This creates an editable table.  eahc row is a form that can be summited to be changed.
// Uses make_ed_array_table
// adds variables:
// editvalues - mark value that is editable.  set editvalues[columnname] = anying makes text box for now, will expand to an object later.
// passvalues - show what info to pass through hidden fielsds. set passvalues[name] = 'value';
function make_editable_table($array_list, $showvalues, $keyvalues, $mode = "ro", $actionpage = "", $editpage = "", $referstring = "", $editvalues, $passvalues, $opts = ""){

		if(stristr($mode,'d') OR stristr($mode,'e')){
		$showvalues['CF__submit'] = 1;
		}
		
			if(count($array_list) > 0){		
				foreach ($array_list as $rowkey => $currentrow){
					$CF__checkval = '';
					$CF__isfirst = 0;	
					
					// GENERATE key string
					foreach ($currentrow as $colkey => $currentcol){
						if(isset($keyvalues[$colkey])){
							if($CF__isfirst == 0){
								$CF__checkval .= "$currentcol";
							}
							else{
								$CF__checkval .= ';';							
								$CF__checkval .= "$currentcol";
							}
							$CF__isfirst ++;
						}
					}// end generate key string for 						
					$row_keys_string = $CF__checkval;
					// Do for each cell in the row
					
					foreach ($currentrow as $colkey => $currentcol){
					
					
						if(isset($editvalues[$colkey])){
							$unique_element_id = $colkey . '_' . $row_keys_string;
							$OV_cellName = "OV_$colkey";
							$OV_cellID = "OV_$unique_element_id";
							
							// produce old_value holder
							$array_list[$rowkey][$colkey] = "<input type='hidden' name='$OV_cellName' id='$OV_cellID' value='$currentcol'>\n";
							
							
							if($editvalues[$colkey]['type'] == 'checkbox'){
								$array_list[$rowkey][$colkey] .= "<input type='hidden' name='$colkey' value='0'>";
								if($currentcol != 0){
									$array_list[$rowkey][$colkey] .= "<input type='checkbox' name='$colkey' id='$unique_element_id' value='1' CHECKED {$editvalues[$colkey]['rawformat']} onClick=\"syncVal('$colkey', '$row_keys_string', '$unique_element_id')\">\n";
								}
								else {
									$array_list[$rowkey][$colkey] .= "<input type='checkbox' name='$colkey' id='$unique_element_id' value='1' {$editvalues[$colkey]['rawformat']} onClick=\"syncVal('$colkey', '$row_keys_string', '$unique_element_id')\">\n";
								}
	
							}
							else if($editvalues[$colkey]['type'] == 'list'){
								$valuesarray = $editvalues[$colkey]['list'];
								$showkey = $editvalues[$colkey]['showkey'];
								$valuekey = $editvalues[$colkey]['valuekey'];
								$selectname = $editvalues[$colkey]['selectname'];
								$dd_opts['id'] = $selectname . '_' . $row_keys_string;
								$dd_opts['onchangeparam'] = "'$colkey', '$row_keys_string', '$unique_element_id'";
								//$dd_opts['id'] = 'NEWID';
								$dd_opts['onchangename'] = 'syncVal';
								
								$select_text = make_array_dd($valuesarray, $selectname, $showkey,$valuekey,$currentcol, 40, $dd_opts);
								$array_list[$rowkey][$colkey] .= "\n$select_text\n";
							
							}
							else{
							$theformat = $editvalues[$colkey]['rawformat'];
								$array_list[$rowkey][$colkey] .= "<input type='text' name='$colkey' id='$unique_element_id' value='$currentcol' {$editvalues[$colkey]['rawformat']} onBlur=\"syncVal('$colkey', '$row_keys_string', '$unique_element_id')\" >\n";
								//$current_session_id = $currentrow['session_id'];
								//$allvalues[$rowkey] ['reviewers'] = "<a href=\"session_reviewerslist.php?flt_session_id=$current_session_id&$urlvarstring\">Edit Reviewers </a>";
							}
						}
				}
				if(stristr($mode,'e')){
					$array_list[$rowkey]['CF__submit'] = "<input type='submit' name='mode' value='Save Row'>";
				}
				if(stristr($mode,'d')){
					$array_list[$rowkey]['CF__submit'] .= "\n<input type='submit' name='mode' value='Delete Row'>";
				}
				if(isset($opts['rowcheck'])){
				// produce semi-colon delimited list of keyvalues


					foreach ($currentrow as $colkey => $currentcol){
						if(isset($keyvalues[$colkey])){
							if($CF__isfirst == 0){
								$CF__checkval .= "$currentcol";
							}
							else{
								$CF__checkval .= ';';							
								$CF__checkval .= "$currentcol";
							}
							$CF__isfirst ++;
						}
					}				
				
					$array_list[$rowkey]['CF__submit'] .= "\n<input type='checkbox' name='addtochecked' value='";

					$array_list[$rowkey]['CF__submit'] .= "$CF__checkval' onCheck='add_trans_sel($CF__checkval)'>";
				
				}
					
					// produce current value key from keyvalues
					foreach ($keyvalues as $keyval => $keyinfo){
						if($keyinfo != 0){
							$this_key_id = $currentrow[$keyval];
							$array_list[$rowkey]['CF__submit'] .= "\n<input type='hidden' name='$keyval' value='$this_key_id'>";
						
						}
					
					//$this_iface_id = $currentrow['iface_id'];
					//$array_list[$rowkey]['submit'] .= "\n<input type='hidden' name='iface_id' value='$this_iface_id'>";
					
					}
					if(!empty($passvalues)){
					foreach($passvalues as $passval => $passinfo){
						$array_list[$rowkey]['CF__submit'] .= "\n<input type='hidden' name='$passval' value='$passinfo'>";
					}}
					
					
					//$array_list[$rowkey]['submit'] .= "\n<input type='hidden' name='mode' value='Edit'>";
					//$array_list[$rowkey]['submit'] .= "\n<input type='hidden' name='flt_infopage_id' value='$flt_infopage_id'>";
					//$array_list[$rowkey]['submit'] .= "\n<input type='hidden' name='flt_iface_type' value='$flt_iface_type'>";
					//$array_list[$rowkey]['submit'] .= "\n<input type='hidden' name='ref_page' value='if_revlist.php'>";
												
					//$currentrow['extra'] = 'TEST2';
			}
	
		}	
		
		
	$list_table =  make_ed_array_table($array_list, $showvalues, $keyvalues, 'ro', $actionpage, $editpage, $referstring);
	
	return $list_table;
}



?>